package com.zbcz.crm.viewmodel

import android.text.TextUtils
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zbcz.crm.CrmApplication
import com.zbcz.crm.bean.DictItem
import com.zbcz.crm.bean.ProjectBean
import com.zbcz.crm.network.CrmApi
import com.zbcz.crm.network.RetrofitManager
import com.zbcz.crm.sp.SharedPreferencesManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class ProjectQueryViewModel : ViewModel() {


    companion object {
        const val TAG = "ProjectQueryViewModel"
    }

    val mDictItemResult: MutableLiveData<List<DictItem>?> = MutableLiveData()

    val mProjectListResult: MutableLiveData<List<ProjectBean>?> = MutableLiveData()


    private val mApi = RetrofitManager.getRetrofit().create(CrmApi::class.java)

    fun getDictionItem(dictCode: String) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                val result = getDictionItemSuspend(dictCode)
                mDictItemResult.postValue(result)
                Log.i(TAG, result.toString())
            }
        }
    }


    private suspend fun getDictionItemSuspend(dictCode: String): List<DictItem>? {
        try {
            val result = mApi?.getDictItems(
                dictCode,
                SharedPreferencesManager.getToken(CrmApplication.mApplication)
            )
            if (result?.success == true) {
                return result.result
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }


    fun getProduct(
        projectName: String?,
        projectType: String?
    ) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                val result = getProductListSuspend(projectName, projectType)?.filter {
                    if (TextUtils.isEmpty(projectType)) {
                        true
                    } else {
                        it.projectType.equals(projectType)
                    }
                }
                mProjectListResult.postValue(result)
            }
        }
    }

    private suspend fun getProductListSuspend(
        projectName: String?,
        projectType: String?
    ): List<ProjectBean>? {
        try {
            val result = mApi?.queryProjectList(
                token = SharedPreferencesManager.getToken(CrmApplication.mApplication),
                projectName = projectName,
                projectType = projectType
            )
            if (result?.success == true) {
                return result.result?.records
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    override fun onCleared() {
        super.onCleared()
    }
}